<script setup lang="ts">
import { getHomeGoodsGuessLikeAPI } from '@/services/home'
import type { PageParams } from '@/types/global'
import type { GuessItem } from '@/types/home'
import { onMounted } from 'vue'
import { ref } from 'vue'

// 分页参数
const pageParams: Required<PageParams> = {
  page: 1,
  pageSize: 10,
}

// 猜你喜欢数据列表
const guessList = ref<GuessItem[]>([])

// 添加一个标记 用来决定是否结束
const isFinish = ref<boolean>(false)

// 获取数据
const getHomeGuessData = async () => {
  // 退出分页判断
  if (isFinish.value === true) {
    return uni.showToast({ icon: 'none', title: '没有更多数据~' })
  }
  const res = await getHomeGoodsGuessLikeAPI(pageParams)
  // 数据追加
  guessList.value.push(...res.result.items)
  // 处理分页条件
  if (pageParams.page < res.result.pages) {
    pageParams.page++
  } else {
    isFinish.value = true
  }
}

// 重置数据
const resetData = () => {
  pageParams.page = 1
  guessList.value = []
  isFinish.value = false
}

// 暴露方法 一个重置  一个加载更多
defineExpose({
  resetData,
  getMore: getHomeGuessData,
})

// 初始化
onMounted(() => {
  getHomeGuessData()
})
</script>

<template>
  <!-- 猜你喜欢 -->
  <view class="caption">
    <text class="text">猜你喜欢</text>
  </view>
  <view class="guess">
    <navigator
      class="guess-item"
      v-for="item in guessList"
      :key="item.id"
      :url="`/pages/goods/goods`"
    >
      <image class="image" mode="aspectFill" :src="item.picture"></image>
      <view class="name"> {{ item.name }} </view>
      <view class="price">
        <text class="small">¥</text>
        <text>{{ item.price }}</text>
      </view>
    </navigator>
  </view>
  <view class="loading-text"> {{ isFinish ? '没有更多数据' : '正在加载...' }} </view>
</template>

<style lang="scss">
@import url(./styles/XtxGuess.scss);
</style>
